package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.utils.RedisListUtil;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
@Slf4j
@Api(tags = "文章接口")
@RequestMapping("/article")
public class ArticleController {


    @Resource
    private IArticleService articleService;
    @Resource
    private  RedisTemplate<String,Object> redisTemplate;
    @Resource
    private IBoardService boardService;
    @Resource
    private RedisListUtil redisListUtil;

    /**
     * 发布新帖
     *
     * @param boardId 板块id
     * @param title   文章标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) throws ExecutionException, InterruptedException {
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //用户已经禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //板块校验
        Board board = boardService.selectById(boardId.longValue());
        //判断该板块是否被禁言
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);  //标题
        article.setContent(content); // 正文
        article.setBoardId(boardId);  // 板块id
        article.setUserId(user.getId());  // 作者id
        //调用service
        articleService.create(article);

        /**
         * 将由于数据发生变化,所以重新查询数据库,将之前的删除掉,重新放入redis
         */
        List<Article> articles = articleService.selectAll();
        redisListUtil.overwriteListInRedis(AppConfig.ARTICLE_KEY,articles);
        //响应成功
        return AppResult.success();
    }


    /**
     * 获取对应板块下的所有帖子列表/获取所有帖子列表
     *
     * @param boardId 为空,获取所有帖子列表,不为空,获取对应板块下的帖子列表
     * @return 帖子列表
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        //定义返回集合
        List<Article> articles;
        //判断redis中key值有没有数据 如果有,则从redis中获取
        if(redisListUtil.keyExists(AppConfig.ARTICLE_KEY) && boardId == null) {
            articles = redisListUtil.getListFromRedis(AppConfig.ARTICLE_KEY);
            log.info("主页内容从redis中获取");
            return AppResult.success(articles);
        }
        //redis中没有key值
        if (boardId == null) {
            //从数据库中查询所有
            articles = articleService.selectAll();
            //将数据库中查询的数据放入redis中
            redisListUtil.saveListToRedis(AppConfig.ARTICLE_KEY,articles);
            log.info("主页内容从数据库中获取");
        } else {
            //查询某个板块
            articles = articleService.selectAllByBoardId(boardId);
        }
        //判断结果是否为空
        if (articles == null) {
            //如果结果为空,就返回一个空数组
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }


    @ApiOperation("根据帖子id查询详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request, @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        Article article = articleService.selectDetailById(id);
        //判断结果是否为空
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if (user.getId().equals(article.getUserId())) {
            article.setOwn(true);  //这里的true使前端动态的显示删除和编辑按钮的
        }
        /**
         * 由于帖子的阅读数量发送了变化,所以需要redis中更新此帖子的阅读数量
         */
        List<Article> articles = articleService.selectAll();
        redisListUtil.overwriteListInRedis(AppConfig.ARTICLE_KEY,articles);
        //返回结果
        return AppResult.success(article);

    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        //得到当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1) {
            //该用户是禁言状态 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子是否有效
        if(article == null) {
            //返回错误
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是不是作者
        if(!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子的状态 -已归档
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            //返回错误
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用service
        articleService.modify(id,title,content);
        //打印日志
        log.info("帖子更新成功 , Article id = "+ id+",  User id = " + user.getId()+ ".");
        /**
         * 将由于数据发生变化,所以重新查询数据库,将之前的删除掉,重新放入redis
          */
        List<Article> articles = articleService.selectAll();
        redisListUtil.overwriteListInRedis(AppConfig.ARTICLE_KEY,articles);
        //返回正确结果
        return AppResult.success();
    }


    /**
     * 根据帖子id进行点赞
     * @param request
     * @param id  帖子id
     * @return
     */
    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request ,
                              @ApiParam("帖子id") @NonNull  @RequestParam("id") Long id) {
        //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //非空校验
        if (id == null || id <= 0) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //调用service
        articleService.thumbsUpById(id);

        /**
         * 将由于数据发生变化,所以重新查询数据库,将之前的删除掉,重新放入redis
         */
        List<Article> articles = articleService.selectAll();
        redisListUtil.overwriteListInRedis(AppConfig.ARTICLE_KEY,articles);
        //返回正确结果即可
        return AppResult.success();
    }


    @PostMapping("/delete")
    @ApiOperation("根据id删除帖子")
    public AppResult deleteById( HttpServletRequest request,
                                 @ApiParam("帖子id") @NonNull @RequestParam("id") Long id) throws ExecutionException, InterruptedException {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //表示用户禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子状态
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1) {
            //帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验当前用户是不是作者
        if(!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service
        articleService.deleteById(id);

        /**
         * 将由于数据发生变化,所以重新查询数据库,将之前的删除掉,重新放入redis
         */
        List<Article> articles = articleService.selectAll();
        redisListUtil.overwriteListInRedis(AppConfig.ARTICLE_KEY,articles);
        //返回
        return AppResult.success();
    }


    @ApiOperation("获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request ,
                                    @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId) {
        //userId为空 从session中获取当前登录的userId
        if(userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User)session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articles = articleService.selectByUserId(userId);
        //返回结果
        return AppResult.success(articles);
    }

    @ApiOperation("帖子搜索")
    @RequestMapping("/search")
    public AppResult<List<Article>> art(@ApiParam("板块id") @RequestParam(value = "boardId", required = false)  Long boardId,
                                        @ApiParam("搜索内容") String artname) {

        if(StringUtil.isEmpty(artname)==null) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<Article> articles = null;
        if(boardId == null) {
            //调用service
            articles = articleService.selectSearch(artname);
            if(articles == null) {
                return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
            }
        } else {
            articles = articleService.selectBoarSearch(artname, boardId);
        }
        return AppResult.success(articles);

    }
}
